package com.qk.management.aop;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.qk.common.Result;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.management.aop.anno.Cacheable;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

/**
 *
 * @author MrZhao
 * @created 2025-10-18 9:19
 * @description 首页数据加载缓存切面
 */
@Slf4j
@Aspect
@Component
@SuppressWarnings("all")
public class CacheableAspect {

    @Autowired
    private StringRedisTemplate redisClient;

    // 定义切点
    @Pointcut("@annotation(com.qk.management.aop.anno.Cacheable)")
    public void pt() {
    }

    // 定义通知
    @Around("pt()")
    public Object cacheable(ProceedingJoinPoint pjp) throws NoSuchMethodException {
        Object returnValue = null;
        String key = null;
        long expireTime = 0L;
        TimeUnit expireTimeUnit = null;
        try {
            // 获取缓存key = 前缀+方法名
            // 获取方法注解和方法名
            // 获取注解
            Class<?> targetClass = pjp.getTarget().getClass();
            // 获取方法名称
            String name = pjp.getSignature().getName();
            // 根据方法名称获取 Method
            Method method = targetClass.getMethod(name);
            // 根据方法获取注解
            Cacheable annotation = method.getAnnotation(Cacheable.class);
            key = annotation.keyPrefix() + name;
            expireTime = annotation.expireTime();
            expireTimeUnit = annotation.expireTimeUnit();
            // 获取缓存
            String jsonStr = redisClient.opsForValue().get(key);
            if (ObjectUtil.isNotEmpty(jsonStr)) {
                return JSONUtil.toBean(jsonStr, method.getReturnType());
            }
        } catch (Exception e) {
            log.error("缓存异常:{}", e.getMessage());
        }
        // 缓存未命中
        try {
            returnValue = pjp.proceed();
        } catch (Throwable e) {
            log.error("查询数据库异常:{}", e.getMessage());
            // 抛出异常直接返回给全局异常处理器
            CommonException.throwCommonException(ParamEnum.OPERATE_ERROR);
        }
        // 将数据加入缓存
        try {
            redisClient.opsForValue().set(key, JSONUtil.toJsonStr(returnValue), expireTime, expireTimeUnit);
        } catch (Exception e) {
            log.error("缓存异常:{}", e.getMessage());
        }
        return returnValue;
    }


}
